package com.jing.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.jing.mall.auth.feign.MemberFeignService;
import com.jing.mall.auth.vo.UserLoginVo;
import com.jing.mall.auth.vo.UserRegistVo;
import com.jing.mall.common.constant.AuthServerConstant;
import com.jing.mall.common.exception.SysException;
import com.jing.mall.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;
    @ResponseBody
    @RequestMapping("/sms/sendcode")
    public R sendSms(@RequestParam("phone") String phone) {
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(s)) {
            Long l = Long.parseLong(s.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60秒内不能再发
                System.out.println("验证码重复了=======");
                return R.error(SysException.SMS_CODE_EXCEPTION.getCode(), SysException.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String yzm = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, yzm, 10, TimeUnit.MINUTES);
        System.out.println("验证码是:::::" + yzm);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            //如果校验出错，跳转到注册页
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://Auth.mall.com/regin.html";
        }
        //注册
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)){
            String s1 = s.split("_")[0];
            if (vo.getCode().equals(s1)){
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vo.getPhone());
                R r = memberFeignService.regist(vo);
                if (r.getCode()==0){
                    //成功
                    return "redirect:http://Auth.mall.com/login.html";
                }else {
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData(new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://Auth.mall.com/regin.html";
                }
            }else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://Auth.mall.com/regin.html";
            }
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://Auth.mall.com/regin.html";
        }

    }
    @PostMapping("/login")
    public String login(UserLoginVo vo,RedirectAttributes redirectAttributes){
        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            //成功
            return "redirect:http://mall.com";
        }else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            //失败
            return "redirect:http://Auth.mall.com/login.html";
        }

    }

}
